import axios from 'axios'
import router from '@/router/index.js'
import { Message } from "element-ui";

const baseURL = process.env.VUE_APP_ADMIN_BASE_URL;

// 弹窗提示
function msgAlert(e) {
  Message.closeAll();
  Message.error(e);
}
// 接口调用成功结果处理
function handleSuccess(res, resolve) {
  console.log(res)
  // 如果接口返回的code值为401,表示用户token过期，需要重新登陆
  if (res.data.code === 401) {
    // 提示
    msgAlert('登陆已失效，请重新登陆');
    // 清空浏览器token

    // 跳转到登陆页
    setTimeout(() => { router.push('/login'); }, 1500);
  } else if (res.data.code === 200) {
    // 结果正常处理
    resolve(res)
  } else {
    // 其他错误，弹窗提示
    msgAlert(res.data.msg);
  }
}

// get方法，用于获取数据请求，参数url，params为对象，返回结果为一个Promise，接then处理正常返回结果
function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: "GET",
      url: url,
      params: params,
      baseURL: baseURL,
      headers: {
        // 请求认证的token
        token: sessionStorage.token ? sessionStorage.token : ""
      }
    })
      .then(res => {
        handleSuccess(res, resolve);
      })
      .catch(err => {
        reject(err);
        msgAlert(err.data.msg);
      });
  });
}

// post方法,Content-Type为application/json方式，参数为对象
function postJson(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: "POST",
      url: url,
      data: JSON.stringify(params),
      baseURL: baseURL,
      headers: {
        "Content-Type": "application/json",
        token: sessionStorage.token ? sessionStorage.token : ""
      }
    })
      .then(res => {
        handleSuccess(res, resolve);
      })
      .catch(err => {
        reject(err);
        msgAlert(err.data.msg);
      });
  });
}

// post方法,application/x-www-form-urlencoded序列化方式传递，参数形式未定
function postXform(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: "POST",
      url: url,
      data: transformRequest(params),
      baseURL: baseURL,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        token: sessionStorage.token ? sessionStorage.token : ""
      }
    })
      .then(res => {
        handleSuccess(res, resolve);
      })
      .catch(err => {
        reject(err);
        msgAlert(err.data.msg);
      });
  });
}

// 表单文件上传
function postUpload(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: "POST",
      url: url,
      data: params,
      baseURL: baseURL,
      headers: {
        "Content-Type": "multipart/form-data",
        token: sessionStorage.token ? sessionStorage.token : ""
      }
    })
      .then(res => {
        handleSuccess(res, resolve);
      })
      .catch(err => {
        reject(err);
        msgAlert(err.data.msg);
      });
  });
}

/**
 * 参数序列化
 * return 参数序列化结果
 */
function transformRequest(obj) {
  if (obj == {}) {
    return null;
  }
  var str = [];
  for (var p in obj) {
    if (obj[p] instanceof Array) {
      obj[p].forEach(element => {
        str.push(encodeURIComponent(p) + "[]=" + encodeURIComponent(element));
      });
    } else {
      if (obj[p] !== undefined && obj[p] !== null) {
        //注：这里必须讲 false 排除在外，否则传入实际false将跳过处理。
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
    }
  }
  return str.join("&");
}

export {
  get,
  postJson,
  postXform,
  postUpload
};
